package com.bfb.adapters;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bfb.GameActivity;
import com.bfb.R;
import com.customComponents.ImageText;

/**
 * 
 * This class acts as a BaseAdapter that is instantiated and applied to the any
 * Gallery created in the game. It is applied to the Gallery using the
 * setAdapter() method.
 * 
 * @author Hadeer Diwan (hadeer.diwan@gmail.com)
 * 
 */
public class ImageAdapter extends BaseAdapter implements OnItemClickListener {

	int mGalleryItemBackground;
	Context mContext;
	public int[] mImageIds;
	private String[] ingredientNames;
	private String tabName;
	public static ArrayList<String> harmfulIngredients;
	public static String toastMessage = "";
	public static Toast toast;
	public static boolean toastOn = false;
	public boolean newToast = true;

	/**
	 * class constructor
	 * 
	 * @param c
	 *            Context for an ImageAdapter instance
	 * @param ingNames
	 *            List of strings containing the names of the images displayed
	 * @param mImageIdss
	 *            List of drawables IDs used in the Gallery
	 * @param tabName
	 *            The name of the tab in which the images are added in
	 * 
	 * @author Hadeer Diwan(hadeer.diwan@gmail.com)
	 * 
	 */
	public ImageAdapter(Context c, String[] ingNames, int[] mImageIdss,
			String tabName) {
		this.tabName = tabName;
		mContext = c;
		this.mImageIds = mImageIdss;
		this.ingredientNames = ingNames;
		// harmfulIngredients =
		// typedArrayToStringArrayList(GameActivity.harmfulIngredients);
		TypedArray attr = mContext.obtainStyledAttributes(R.styleable.Gallery1);
		mGalleryItemBackground = attr.getResourceId(
				R.styleable.Gallery1_android_galleryItemBackground, 0);
		attr.recycle();
	}

	/**
	 * 
	 * @param toastMessage
	 *            the string to be shown in the toast
	 * 
	 *            This method is used to set the string that is shown in the
	 *            toast according to the event, meaning that for every event
	 *            there is a different message to be shown to the user
	 * 
	 * @author Hadeer Diwan(hadeer.diwan@gmail.com)
	 */

	public void toast(String toastMessage) {

		toast = Toast.makeText(mContext, toastMessage, Toast.LENGTH_SHORT);
		toast.setText(toastMessage);
		toast.show();
	}

	/**
	 * 
	 * This method is responsible for checking if the user has selected another
	 * item from the same tab. It starts by checking if the current tab is one
	 * of the tabs that contain harmful ingredients by calling
	 * {@link ImageAdapter#checkTabName(String)} If that tab contains harmful
	 * ingredients,that might affect the health of the user, the user is
	 * notified by a toast that is shown using this method
	 * {@link ImageAdapter#toast(String) }
	 * 
	 * @author Hadeer Diwan (hadeer.diwan@gmail.com)
	 */

	public void checkSelectedItems() {
		Log.e("tab name", this.tabName);
		if (checkTabName(tabName)) {
			ArrayList<String> ItemsInTabNow = listOfStringsToArrayList(ingredientNames);
			int size = GameActivity.selectedIngredientNamesList.size();
			if (size > 1) {
				int last = size - 1;
				int position = ItemsInTabNow
						.indexOf(GameActivity.selectedIngredientNamesList.get(
								last).toString());
				ItemsInTabNow.remove(position);
				for (int i = 0; i < size; i++) {
					for (int j = 0; j < ItemsInTabNow.size(); j++) {
						if (GameActivity.selectedIngredientNamesList.get(i)
								.toString()
								.equals(ItemsInTabNow.get(j).toString())) {
							toast(toastMessage);
							toastOn = true;
							Log.e("toast message", toastMessage);
							break;
						}
					}
				}
			}
		}
	}

	/**
	 * 
	 * @param tabName
	 *            the name of the tab the user is currently viewing
	 * 
	 *            This method is used to set the message that appears in the
	 *            toast depending on the tab the user is currently viewing. It
	 *            sets the toast message to a string that is retrieved from the
	 *            strings.xml file
	 * 
	 * @author Your_name (your_email)
	 */
	public void getToastmessage(String tabName) {
		if (tabName.equalsIgnoreCase(GameActivity.ingredientTypes[1]))
			toastMessage = mContext.getResources().getString(R.string.dessert);

		else if (tabName.equalsIgnoreCase(GameActivity.ingredientTypes[3]))
			toastMessage = mContext.getResources().getString(R.string.meat);

		else if (tabName.equalsIgnoreCase(GameActivity.ingredientTypes[6]))
			toastMessage = mContext.getResources().getString(R.string.poultry);

		else if (tabName.equalsIgnoreCase(GameActivity.ingredientTypes[4])
				|| tabName.equalsIgnoreCase(GameActivity.ingredientTypes[5]))
			toastMessage = mContext.getResources().getString(
					R.string.carbohydrates);

		else if (tabName.equalsIgnoreCase(GameActivity.ingredientTypes[7]))
			toastMessage = mContext.getResources().getString(R.string.seaFood);
	}

	/**
	 * 
	 * @param tabName
	 *            the name of the tab the user is currently viewing
	 * 
	 * @return boolean
	 * 
	 *         This method is used to check if the tab that the user is urrently
	 *         viewing contains harmful ingredients for his health or not
	 * @author Hadeer Diwan (hadeer.diwan@gmail.com)
	 */

	public boolean checkTabName(String tabName) {
		harmfulIngredients = typedArrayToStringArrayList(GameActivity.harmfulIngredients);
		if (harmfulIngredients.contains(tabName)) {
			getToastmessage(tabName);
			return true;
		}

		else
			return false;
	}

	/**
	 * 
	 * @param ta
	 *            typed array entered
	 * @return an array of strings containing the elements in the TypedArry
	 * 
	 * @author Hadeer Diwan (hadeer.diwan@gmail.com)
	 */

	public static ArrayList<String> typedArrayToStringArrayList(TypedArray ta) {
		ArrayList<String> al = new ArrayList<String>();
		for (int i = 0; i < ta.length(); i++)
			al.add(ta.getString(i));
		return al;

	}

	/**
	 * 
	 * @param s
	 *            list of strings
	 * @return an array list containing the elements in the list of strings.
	 * 
	 * @author Hadeer Diwan (hadeer.diwan@gmail.com)
	 */

	public ArrayList<String> listOfStringsToArrayList(String[] s) {
		ArrayList<String> al = new ArrayList<String>();
		for (int i = 0; i < s.length; i++) {
			al.add(s[i]);
		}
		return al;

	}

	@Override
	public int getCount() {
		return mImageIds.length;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * This method creates a new View for each image added to the ImageAdapter.
	 * It creates a Image text that contains an image and a text. The image is
	 * the image of the ingredient and the text is the name of the ingredient
	 * 
	 * @auther Hadeer Diwan(hadeer.diwan@gmail.com)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView != null) {
			return convertView;
		}

		ImageText galleryItem = new ImageText(mContext, null);
		galleryItem.setText(ingredientNames[position]);
		// galleryItem.setResource(mImageIds[position]);
		// galleryItem.setBackgroundResource(mGalleryItemBackground);
		// galleryItem.setLayoutParams(new Gallery.LayoutParams(
		// LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));

		galleryItem.setText(ingredientNames[position]);
		ImageView imageView = galleryItem.getImageView();
		imageView.setImageResource(mImageIds[position]);
		imageView.setLayoutParams(new LinearLayout.LayoutParams(150, 120));
		imageView.setBackgroundResource(mGalleryItemBackground);
		TextView tv = galleryItem.getTextView();
		tv.setText(ingredientNames[position]);
		tv.setGravity(Gravity.CENTER);
		tv.setTextSize(10);
		tv.setPadding(0, 0, 0, 40);

		return galleryItem;
	}

	/**
	 * Overridden {@link OnItemClickListener}. When an item is clicked, the list
	 * of selected ingredients is updated. If the item was previously added,
	 * then it is removed. If it is not found in the list then it is added. The
	 * {@link TextView} on the plate of the {@link GameActivity} is updated with
	 * the new ingredient list. It will also call checkSelectItems().
	 * 
	 * @param parent
	 * @param view
	 * @param position
	 * @param id
	 * 
	 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
	 * 
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (toastOn == true) {
			toast.cancel();
			toastOn = false;
		}
		String ingName = ingredientNames[position];
		if (!GameActivity.selectedIngredientNamesList.contains(ingName)) {
			GameActivity.selectedIngredientNamesList.add(ingName);
		} else {
			GameActivity.selectedIngredientNamesList.remove(ingName);

		}
		checkSelectedItems();
		String text = GameActivity.selectedIngredientNamesList.toString();
		GameActivity.selectedIngredientsTextView.setText(text.substring(1,
				text.length() - 1));
	}
}

/**
 * This commented part is the same class but with the functionality of adding
 * photos to the plate. It is still very buggy.
 * 
 * package com.bfb;
 * 
 * import android.content.Context; import android.content.res.TypedArray; import
 * android.view.View; import android.view.View.OnClickListener; import
 * android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import
 * android.widget.AdapterView; import
 * android.widget.AdapterView.OnItemClickListener; import
 * android.widget.BaseAdapter; import android.widget.Gallery; import
 * android.widget.ImageView;
 * 
 * import com.yarab.R;
 * 
 * public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground;
 * Context mContext; public int[] mImageIds; public String[] fileNames; public
 * int currentPosition; public OnItemClickListener listener;
 * 
 * public ImageAdapter(Context c, String[] fileNamess, int[] mImageIdss) {
 * mContext = c; this.mImageIds = mImageIdss; this.fileNames = fileNamess;
 * TypedArray attr = mContext.obtainStyledAttributes(R.styleable.Gallery1);
 * mGalleryItemBackground = attr.getResourceId(
 * R.styleable.Gallery1_android_galleryItemBackground, 0); attr.recycle();
 * listener = new OnItemClickListener() { public void onItemClick(AdapterView<?>
 * arg0, View v, int position, long id) { // ImageAdapter ia = (ImageAdapter)
 * GameActivity.ingredientsGrid // .getAdapter(); currentPosition = position; if
 * (!GameActivity.dishIngredientsFileNames.contains(" " + fileNames[position] +
 * " ")) { GameActivity.dishIngredientsFileNames += fileNames[position] + " ";
 * ImageView test = new ImageView(mContext);
 * test.setImageResource(mImageIds[position]); test.setOnClickListener(new
 * OnClickListener() {
 * 
 * public void onClick(View v) { GameActivity.dishIngredientsFileNames =
 * GameActivity.dishIngredientsFileNames .replaceAll(" " +
 * fileNames[currentPosition] + " ", " ");
 * GameActivity.ingredientsGrid.removeView(v); } });
 * GameActivity.ingredientsGrid.addView(test); }
 * GameActivity.ingredientsGrid.invalidate(); //
 * GameActivity.selectedIngredientsTextView //
 * .setText(GameActivity.dishIngredientsFileNames); } }; }
 * 
 * public int getCount() { return mImageIds.length; }
 * 
 * public Object getItem(int position) { return position; }
 * 
 * public long getItemId(int position) { return position; }
 * 
 * public View getView(int position, View convertView, ViewGroup parent) {
 * GalleryItemView galleryItem = new GalleryItemView(mContext,
 * fileNames[position]); galleryItem.setImageResource(mImageIds[position]);
 * galleryItem.setScaleType(ImageView.ScaleType.FIT_XY);
 * galleryItem.setBackgroundResource(mGalleryItemBackground);
 * galleryItem.setLayoutParams(new Gallery.LayoutParams(100, 100)); return
 * galleryItem; } }
 */
